<template>
	<view class="router-view container bcl-active">
		<!-- 雇佣标题 -->
		<view v-if="type == 6 || type == 7">
			<!-- 标题 -->
			<view class="title bold fz-15 mt-10">一句话说明TA需要干什么</view>

			<view class="uni-input mt-20">
				<input type="text" v-model="serviceTitle" />
			</view>
		</view>

		<!-- 标题 -->
		<view class="title bold fz-15 mt-10">{{ titles[type] }}</view>

		<!-- 文本域 -->
		<textarea class="border border-deep bcl-white radius mt-20" :placeholder="placeholders[type]" :maxlength="maxLength"
		 v-model="content"></textarea>

		<view class="box box-between fz-12 cl-second mt-10">
			<text></text>
			<text>{{ content.length }}/{{ maxLength }}</text>
		</view>

		<!-- 雇佣联系方式 -->
		<view v-if="type == 6 || type == 7">
			<!-- 标题 -->
			<view class="title bold fz-15 mt-10">填写联系方式</view>

			<view class="uni-input mt-20">
				<input type="number" v-model="tel" />
			</view>
		</view>

		<!-- 雇佣预算 -->
		<view v-if="type == 6 || type == 7">
			<!-- 标题 -->
			<view class="title bold fz-15 mt-10">雇佣预算</view>

			<view class="uni-input box mt-20">
				<input type="number" v-model="serviceMoney" />
				<text>元</text>
			</view>
		</view>

		<!-- 投标的报价 -->
		<view v-if="type == 4">
			<view class="title bold fz-15 mt-20">报价</view>

			<view class="uni-input mt-20">
				<input type="number" v-model="money" />
			</view>
		</view>

		<!-- 完成时间 -->
		<view v-if="(type == 1 && role == 'employer') || type == 6 || type == 7">
			<view class="title bold fz-15 mt-20">修改完成时间</view>

			<!-- 日期选择 -->
			<div class="uni-input mt-20">
				<picker mode="date" :value="date" @change="onDateChange">
					<text>{{ date }}</text>
				</picker>
			</div>

			<!-- 时间选择 -->
			<div class="uni-input" v-if="type == 1">
				<picker mode="time" start="09:01" end="21:01" :value="time" @change="onTimeChange">
					<text>{{ time }}</text>
				</picker>
			</div>
		</view>

		<!-- 上传按钮 -->
		<view class="p-10" style=" padding-left: 0;align-items: center;color: #c3c3c3;" v-if="type != 5">

			<view class="addBox uni-upload-button pointer pointer-filter" ref="input" style="background:#fff;" @click="onChooseImage">

				<text class="icon icon-annex fz-20"></text>
				<text class="fz-12" style="margin-left: 0;">任务附件</text>

			</view>
			<!-- <view class="filesBox" v-if="fileList.length > 0" style="display:block;padding:10px 0 0 0;">
		<view class="fileslist" v-for="item in fileList">
				<text class="upname">{{item}}</text>
		</view>
	</view> -->

		</view>
		<!-- <view
      class=" pointer pointer-filter bcl-white mt-20"
      @click="uploadFile"
      v-if="type != 5"
    > -->




		<!-- <text class="icon icon-annex fz-20"></text> -->
		<!-- <text class="fz-12" style="margin-left: 0;">任务附件1111</text> -->
		<!-- </view> -->

		<!-- 附件列表 -->
		<view class="file-list mt-10">
			<view class="item mb-5" v-for="(item, index) in fileList" :key="index">
				<uni-file :item="item" @delete="deleteFile(index)"></uni-file>
			</view>
		</view>

		<view class="box box-column-center fz-12 mt-20" v-if="type == 3">
			<checkbox-group @change="onProtocolChange">
				<label>
					<checkbox value="同意" :checked="protocol" />
					<text class="cl-second middle">我已阅读并同意</text>
				</label>
			</checkbox-group>
			<navigator url="/user/plan?type=0">《项目交付协议》</navigator>
		</view>

		<!-- 确认提交 -->
		<view class="uni-footer bcl-main-new cl-white text-center pointer pointer-filter" @tap="submitAction">确认提交</view>
	</view>
</template>

<script>
	import {
		contribute,
		deliver,
		createUpdate
	} from "@/apis/task";
	import {
		feedback
	} from "@/apis/user";
	import {
		employ
	} from "@/apis/service";
	import {
		chooseImage,
		chooseFile
	} from "@/utils/choose";
	import uniFile from "@/components/file";
	import regexp from "@/utils/regexp";

	import {
		getconfig
	} from "@/apis/app";

	import {
		getFileName
	} from "@/apis/task";

	export default {

		data() {
			let currentDate = this.getDate({
				format: true
			});

			let currentTime = this.getTime();

			return {
				serviceTitle: "",
				serviceMoney: "",
				content: "",
				money: "",
				tel: "",
				fileList: [],
				maxLength: 200,

				titles: {
					1: "修改内容",
					2: "回复内容",
					3: "稿件说明",
					4: "稿件说明",
					5: "反馈内容",
					6: "详细描述下您的需求",
					7: "详细描述下您的需求"
				},
				placeholders: {
					1: "请输入修改内容~",
					2: "补充内容~",
					3: "稿件说明文字~",
					4: "稿件说明文字~",
					5: "您要反馈的内容~",
					6: "描述内容~",
					7: "描述内容~"
				},
				navigationBarTitles: {
					1: "创建修改",
					2: "修改回复",
					3: "项目交付",
					4: "我要投标",
					5: "反馈建议",
					6: "雇佣页面",
					7: "雇佣页面"
				},

				type: 1,
				taskId: "",
				taskType: "",
				taskSort: "",
				role: "",
				recordId: "",
				serviceId: "",
				employeeId: "",

				date: currentDate,
				time: currentTime,
				protocol: true,
				filelds: []
			};
		},

		onLoad(options) {
			let {
				type,
				taskId,
				taskType,
				taskSort,
				role,
				recordId,
				employeeId,
				serviceId,
				serviceTitle,
				serviceMoney
			} = options;
			this.type = Number(type);
			this.taskId = taskId;
			this.taskType = taskType;
			this.taskSort = taskSort;
			this.role = role;
			this.recordId = recordId;
			this.serviceId = serviceId;
			this.serviceTitle = serviceTitle;
			this.serviceMoney = serviceMoney;
			this.employeeId = employeeId;

			// 修改页面标题
			uni.setNavigationBarTitle({
				title: this.navigationBarTitles[this.type]
			});
		},

		mounted() {},
		computed: {
			fileIDs() {
				return this.filelds.join(",");
			}
		},
		methods: {

			/*
			 * 删除文件
			 */
			deleteFile(index) {
				console.log(index);
				this.fileList.splice(index, 1);
				this.filelds.splice(index, 1);
			},

			async onChooseImage() {
				let getconfigs = await getconfig();
				uni.setStorageSync("accessid", getconfigs.data.accessid);
				uni.setStorageSync("callback", getconfigs.data.callback);
				uni.setStorageSync("dir", getconfigs.data.dir);
				uni.setStorageSync("expire", getconfigs.data.expire);
				uni.setStorageSync("host", getconfigs.data.host);
				uni.setStorageSync("policy", getconfigs.data.policy);
				uni.setStorageSync("signature", getconfigs.data.signature);
				let _this = this;
				uni.chooseImage({
					count: 5,
					success: function(res) {
						uni.showLoading({
							title: "正在上传..",
							mask: true,
						});
						let paths = res.tempFiles;
						var path = res.tempFiles[0].path;
						var size = res.tempFiles[0].size;
						let sub = path.lastIndexOf('/');
						var fileName = path.substring(sub + 1);
						var namelength = fileName.length; //取到文件名长度
						var ossUrl = 'https://zhihuawang.oss-cn-beijing.aliyuncs.com'
						console.log(fileName);
						let key = uni.getStorageSync("dir") + new Date().getTime() + '.' + fileName;
						uni.uploadFile({
							url: ossUrl, //输入你的bucketname.endpoint
							filePath: path,
							// fileType: 'image',
							name: 'file',
							formData: {
								name: '22222',
								key: key,
								policy: uni.getStorageSync("policy"), // 输入你获取的的policy
								OSSAccessKeyId: uni.getStorageSync("accessid"), // 输入你的AccessKeyId
								success_action_status: '200', // 让服务端返回200,不然，默认会返回204
								signature: uni.getStorageSync("signature"), // 输入你获取的的signature
								callback: uni.getStorageSync("callback"),
							},
							success: function(resp) {

								if (resp.statusCode === 200) {
									let params = {
										filename: key,
										filesize: size,
										def_filename: fileName
									};
									getFileName(params).then(reps => {
										uni.hideLoading();
										console.log(reps);
										if (reps.code === 200) {
											_this.$toast("上传成功");
											_this.filelds.push(reps.data.attach_id)
											let obj = fileName.split('.');
											_this.fileList.push({
												name: key,
												url: path,
												type: 'jpg'  
											});
										} else {
											_this.$toast("上传失败");
										}
									}, error => {

									});

								}
							},
							fail: function(error) {
								console.log(error);
							}
						});
						// 预览图片
					}
				});
			},

			async uploadFile() {
				var _this = this
				let getconfigs = await getconfig();
				uni.setStorageSync("accessid", getconfigs.data.accessid);
				uni.setStorageSync("callback", getconfigs.data.callback);
				uni.setStorageSync("dir", getconfigs.data.dir);
				uni.setStorageSync("expire", getconfigs.data.expire);
				uni.setStorageSync("host", getconfigs.data.host);
				uni.setStorageSync("policy", getconfigs.data.policy);
				uni.setStorageSync("signature", getconfigs.data.signature);
			},

			uploadAPI(path) {
				this.uploadFile()
				var _this = this
				var fData = new FormData();
				let paths = path;
				var pathName = paths.name
				var pathSize = paths.size
				var fileName = pathName
				var first = fileName.lastIndexOf("."); //取到文件名开始到最后一个点的长度
				var namelength = fileName.length; //取到文件名长度
				var filesuffix = fileName.substring(first + 1, namelength); //截取获得后缀名
				_this.timesdata = new Date().getTime()
				fData.append("name", 22222);
				fData.append("key", uni.getStorageSync("dir") + _this.timesdata + '.' + filesuffix);
				fData.append("policy", uni.getStorageSync("policy"));
				fData.append("OSSAccessKeyId", uni.getStorageSync("accessid"));
				fData.append("success_action_status", 200);
				fData.append("signature", uni.getStorageSync("signature"));
				fData.append("callback", uni.getStorageSync("callback"));
				fData.append("file", path);
				var xhr = new XMLHttpRequest();
				// var surl = util.commonUrl() + api.uploadUrl;
				var surl = 'https://zhihuawang.oss-cn-beijing.aliyuncs.com';

				uni.showLoading({
					title: '上传中',
					mask: false

				})

				xhr.open("POST", surl, true);
				xhr.onload = function(e) {
					//  alert(1)
					// console.log("上传成功",e.status); //上传成功
				};
				xhr.onreadystatechange = () => {
					// console.log("12121212",xhr.onreadystatechange)
					if (xhr.readyState == 4 && xhr.status == 200) { //上传后台成功

						uni.hideLoading()
						let params = {
							filename: uni.getStorageSync("dir") + _this.timesdata + '.' + filesuffix,
							filesize: uni.getStorageSync("pathSize"),
							def_filename: pathName
						};
						_this.getFileNamedata(params, pathName)
						// var res =JSON.parse(xhr.responseText)
						// res.datas.names  = fileName
						_this.fileList.push(fileName); // 上传成功后放进fileList数组用于展示

					} else {
						uni.hideLoading()
					}
				}


				// 这里设置请求头，做的时候遇到一个问题，明明上传的是FormData，可是在请求中变成了request payload,后台需要的是FormData，解决方法，设置enctype为multipart/form-data，不要设置Content-Type，切记直接不设置Content-Type
				xhr.setRequestHeader('enctype', "multipart/form-data");
				// xhr.setRequestHeader('Authorization',util.getToken());
				xhr.send(fData)

			},

			/*
			 * 提交分发
			 */
			async submitAction() {
				if (!this.content) return this.$toast("内容不能为空~");
				if (this.type == 3 && !this.protocol) return this.$toast("请先同意协议~");
				if (this.type == 4 && !this.money) return this.$toast("请输入报价~");
				if (this.type == 6 || this.type == 7) {
					if (!this.serviceTitle) return this.$toast("请输入一句话说明~");
					if (!regexp.tel.test(this.tel))
						return this.$toast("请输入正确的手机号~");
					if (!this.serviceMoney) return this.$toast("请输入雇佣预算~");
				}
				switch (this.type) {
					case 1:
						// 创建修改记录
						this.createUpdate();
						break;
					case 2:
						break;
					case 3:
						// 交付稿件
						this.deliver();
						break;
					case 4:
						// 我要投标
						this.contribute();
						break;
					case 5:
						// 意见反馈
						this.feedback();
						break;
					case 6:
						// 立即雇佣
						this.employ();
						break;
					case 7:
						// 立即购买
						this.employ();
						break;
					default:
						break;
				}
			},

			/*
			 * 创建修改记录
			 */
			async createUpdate() {
				let params = {
					desc: this.content,
					task_id: this.taskId,
					file_id: this.fileIDs,
					bc_id: this.role == "employer" ? 0 : this.recordId,
					wanchengtime: `${this.date} ${this.time}`
				};

				if (this.role != "employer") delete params.wanchengtime;

				let {
					code,
					data
				} = await createUpdate(params);

				if (code == 200) {
					this.$toast(
						this.role == "employer" ? "创建成功" : "回复成功",
						"success"
					);
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			},

			/*
			 * 我要投标
			 */
			async contribute() {
				console.log(this.type);
				let params = {
					desc: this.content,
					task_id: this.taskId,
					file_id: this.fileIDs,
					price: this.money
				};
				console.log(params)

				let {
					code,
					data
				} = await contribute(params);

				if (code == 200) {
					this.$toast("投标成功", "success");
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			},

			/*
			 * 交付稿件
			 */
			async deliver() {
				let params = {
					desc: this.content,
					task_id: this.taskId,
					file_id: this.fileIDs,
					sort: this.taskSort
				};

				let {
					code,
					data
				} = await deliver(params);

				if (code == 200) {
					this.$toast("交付成功", "success");
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			},

			/**
			 * 立即雇佣
			 */
			async employ() {
				let params = {
					title: this.serviceTitle,
					desc: this.content,
					phone: this.tel,
					delivery_deadline: this.date,
					bounty: this.serviceMoney,
					employee_uid: this.employeeId,
					file_id: this.fileIDs
				};

				if (this.type == 7) params.service_id = this.serviceId;

				let {
					code,
					data
				} = await employ(params);

				if (code == 200) {
					this.$toast("创建订单成功", "success");

					setTimeout(() => {
						uni.redirectTo({
							url: `/pay/pay?type=4&employId=${data.employ_id}&orderId=${data.order_id}`
						});
					}, 1000);
				}
			},

			/**
			 * 意见反馈
			 */
			async feedback() {

				let datas = uni.getStorageSync("userInfo")
				console.log(datas)
				let params = {
					nickname: datas.nickname,
					phone: datas.mobile,
					desc: this.content
				};
				let {
					code,
					data
				} = await feedback(params);
				if (code === 200) {
					this.$toast("提交成功，感谢您的反馈");
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			},

			/*
			 * 上传文件
			 */
			// async uploadFile() {
			//   // #ifdef H5
			//   let files = await chooseImage(1);
			//   // #endif

			//   // #ifndef H5
			//   let files = await chooseFile(1);
			//   // #endif

			//   this.files.push(files[0]);
			// },

			onProtocolChange(event) {
				let value = event.detail.value[0];
				this.protocol = !!value;
			},

			// 日期更改回调
			onDateChange(event) {
				this.date = event.target.value;
			},

			// 时间更改回调
			onTimeChange(event) {
				this.time = event.target.value;
			},

			// 获取日期
			getDate(type) {
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === "start") {
					year = year - 60;
				} else if (type === "end") {
					year = year + 2;
				}
				month = month > 9 ? month : "0" + month;
				day = day > 9 ? day : "0" + day;
				return `${year}-${month}-${day}`;
			},

			// 获取日期
			getTime() {
				let date = new Date();
				let hour = date.getHours();
				let minute = date.getMinutes();

				if (String(hour).length == 1) hour = `0${hour}`;
				if (String(minute).length == 1) minute = `0${minute}`;

				return `${hour}:${minute}`;
			}
		},

		components: {
			uniFile
		}
	};
</script>

<style lang="scss" scoped>
	.router-view {
		padding-bottom: 140upx;
	}
</style>
